package com.zsc.edu.gateway.framework.websocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zsc.edu.gateway.modules.iot.device.service.DeviceService;
import com.zsc.edu.gateway.modules.iot.product.service.ProductService;
import com.zsc.edu.gateway.modules.iot.record.service.RecordDataService;
import lombok.AllArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.function.Supplier;

@Component
@AllArgsConstructor
public class DataPushTask {
    private final DeviceService deviceService;
    private final RecordDataService recordDataService;
    private final ProductService productService;
    private final ObjectMapper objectMapper;
    private final DeviceWebSocketHandler deviceHandler;
    private final RecordWebSocketHandler recordHandler;
    private final ProductWebSocketHandler productHandler;

    @Scheduled(fixedRate = 3000)
    public void pushData() {
        pushAndBroadcast(deviceService::status, deviceHandler);
        pushAndBroadcast(recordDataService::recordDataStatus, recordHandler);
        pushAndBroadcast(productService::status, productHandler);
    }

    private void pushAndBroadcast(Supplier<Object> dataSupplier, BaseWebSocketHandler handler) {
        try {
            Object status = dataSupplier.get();
            String json = objectMapper.writeValueAsString(status);
            handler.broadcast(json);
        } catch (Exception e) {
            // 生产环境应使用日志记录
            e.printStackTrace();
        }
    }
}